package com.lyf.juc.practice.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 利用CAS的底子实现基本的自旋锁--
 * 需求：
 * 线程A进入抢锁，停留几秒，线程B进入发现已被抢了，则自旋，直到A释放
 * @author LYF
 * @date 2022/7/12
 */
//class SpinLock extends Thread{
//    //volatile Object myLock = new Object();
//    AtomicBoolean atomicBoolean = new AtomicBoolean(false);
//    boolean tryLock(){
//        do{
//            System.out.println(Thread.currentThread().getName()+"::抢锁");
//        }while (!atomicBoolean.getAndSet(true));
//        System.out.println(Thread.currentThread().getName()+"::抢锁成功");
//        return true;
//    }
//}
public class SpinLockTest {

    AtomicReference<Thread> atomicReference = new AtomicReference<>(null);

    void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"::come in");
        while (!atomicReference.compareAndSet(null,thread)){
             // 若已被抢，则自旋等待
        }
    }
    void unlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"::come in");
        while (!atomicReference.compareAndSet(thread,null)){
            // 若已被抢，则自旋等待
        }
        System.out.println(thread.getName()+"::释放锁");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockTest spinLockTest = new SpinLockTest();
        new Thread(()->{
            spinLockTest.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockTest.unlock();
        },"A").start();

        TimeUnit.MILLISECONDS.sleep(300);

        new Thread(()->{
            spinLockTest.lock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockTest.unlock();
        },"B").start();
    }

}
